package zy.controller.base;

import java.io.File;
import java.io.IOException;
import java.io.PrintWriter;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import jxl.Workbook;
import jxl.write.WritableWorkbook;
import jxl.write.WriteException;

import org.apache.commons.io.FileUtils;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import zy.controller.BaseController;
import zy.entity.PageData;
import zy.entity.base.color.T_Base_Color;
import zy.entity.sys.improtinfo.T_Import_Info;
import zy.entity.sys.user.T_Sys_User;
import zy.service.base.color.ColorService;
import zy.util.CommonUtil;
import zy.util.DateUtil;
import zy.util.ExcelImportUtil;
import zy.util.StringUtil;
import zy.vo.base.ColorVO;

import com.alibaba.fastjson.JSONObject;
@Controller
@RequestMapping("base/color")
public class ColorController extends BaseController{
	@Resource
	private ColorService colorService;
	
	@RequestMapping(value = "/to_list", method = RequestMethod.GET)
	public String to_list() {
		return "base/color/list";
	}
	@RequestMapping("to_list_dialog")
	public String to_list_dialog() {
		return "base/color/list_dialog";
	}
	@RequestMapping(value = "/to_update", method = RequestMethod.GET)
	public String to_update(@RequestParam Integer cr_id,Model model) {
		T_Base_Color color = colorService.queryByID(cr_id);
		if(null != color){
			model.addAttribute("color",color);
		}
		return "base/color/update";
	}
	
	@RequestMapping("to_add")
	public String to_add() {
		return "base/color/add";
	}
	
	@RequestMapping("to_import_color")
	public String to_import_color() {
		return "base/color/import_color";
	}
	
	@RequestMapping(value = "page", method = { RequestMethod.GET, RequestMethod.POST })
	@ResponseBody
	public Object page(HttpServletRequest request,HttpSession session) {
		String name = request.getParameter("searchContent");
		String page = request.getParameter("page"); // 页码
        String rows = request.getParameter("rows"); // 每页条数
        String sidx = request.getParameter("sidx");
        String sord = request.getParameter("sord");
        int pageIndex = 1;
        int pageSize = super.pagesize;
        if (org.apache.commons.lang.StringUtils.isNotEmpty(page)) {
        	pageIndex = Integer.parseInt(page);
        	pageIndex = pageIndex == 0 ? 1 : pageIndex;
        }
        if (org.apache.commons.lang.StringUtils.isNotEmpty(rows)) {
        	pageSize = Integer.parseInt(rows);
        }
        T_Sys_User user = getUser(session);
        Map<String,Object> param = new HashMap<String, Object>();
        param.put(CommonUtil.COMPANYID, user.getCompanyid());
        param.put("name", StringUtil.decodeString(name));
        param.put(CommonUtil.PAGESIZE, pageSize);
        param.put(CommonUtil.PAGEINDEX, pageIndex);
        param.put(CommonUtil.SIDX, sidx);
        param.put(CommonUtil.SORD, sord);
		PageData<T_Base_Color> pageData = colorService.page(param);
		return ajaxSuccess(pageData, "查询成功, 共" + pageData.getList().size() + "条数据");
	}
	
	@RequestMapping(value = "save", method = { RequestMethod.GET, RequestMethod.POST })
	@ResponseBody
	public Object save(T_Base_Color color,HttpServletRequest request,HttpSession session) {
		 T_Sys_User user = getUser(session);
		 color.setCompanyid(user.getCompanyid());
		 color.setCr_spell(StringUtil.getSpell(color.getCr_name()));
		 Integer id = colorService.queryByName(color);
		 if(null != id && id > 0){
			return result(EXISTED);
		 }else{
			 colorService.save(color);
			 return ajaxSuccess(color);
		 }
	}
	
	@RequestMapping(value = "save_to_product", method = { RequestMethod.GET, RequestMethod.POST })
	@ResponseBody
	public Object save_to_product(T_Base_Color color,String pd_code,HttpSession session) {
		 T_Sys_User user = getUser(session);
		 color.setCompanyid(user.getCompanyid());
		 color.setCr_spell(StringUtil.getSpell(color.getCr_name()));
		 colorService.save_to_product(color, pd_code);
		 return ajaxSuccess();
	}
	
	@RequestMapping(value = "save_import_color", method = RequestMethod.POST,produces = "text/html; charset=utf-8")
	@ResponseBody
	public Object save_import_color(MultipartFile excel,HttpServletRequest request,HttpSession session)throws IOException {
		if (excel == null || excel.getSize() <= 0) {
			return ajaxFail("请选择需要导入的文件！"); 
		}
		Map<String,Object> param = new HashMap<String, Object>();
		Workbook sourceWorkBook = null;
		Workbook wb_error = null;
		WritableWorkbook wb = null;
		
		try {
			T_Sys_User user = getUser(session);
			param.put("companyid", user.getCompanyid());
			param.put("us_id", user.getUs_id());
			//根据商家编号、用户编号及当前时间生成文件名
			SimpleDateFormat format = new SimpleDateFormat("yyyyMMddHHmmss");
			String fileName = "color_" + user.getCompanyid() + (user.getUs_id() + format.format(new Date())) + ".xls";
			
			// 复制客户端文件到服务器临时文件夹进行处理,处理完以后删除
			String temp_uploaddir = CommonUtil.CHECK_BASE + CommonUtil.EXCEL_PATH;
			String toFilePath = temp_uploaddir + File.separator + fileName;
			File savefile = new File(toFilePath);
			if (!savefile.getParentFile().exists()) {
				savefile.getParentFile().mkdirs();
			}
			excel.transferTo(savefile);
			
			// Excel 模板文件路径，把模板文件复制，然后作为错误文件进行数据追加
			String relPath = session.getServletContext().getRealPath("resources");
			String excel_member_template = relPath + File.separator + "excel" + File.separator + CommonUtil.COLORLEADING;
			
			// 错误文件名称
			String errFileName = "fail" + fileName;
			String errorFilePath = temp_uploaddir + File.separator + errFileName;
			File excel_template = new File(excel_member_template);// 原有Excel 模板文件
			File errorFile = new File(errorFilePath);// 生成的错误文件路径
			// 把模板文件复制给错误文件
			FileUtils.copyFile(excel_template, errorFile);
			
			sourceWorkBook = Workbook.getWorkbook(savefile);// 要导入的Excel
			wb_error = Workbook.getWorkbook(errorFile);
			wb = Workbook.createWorkbook(errorFile, wb_error);
			Map<String, Object> result = colorService.parseSavingCardInfoExcel(sourceWorkBook, wb, user.getCompanyid());
			wb.write();
			
			ExcelImportUtil.deleteFile(savefile);
			int success = (Integer)(result.get("success"));// 导入成功条数
			int fail = (Integer)(result.get("fail"));// 导入失败条数
			List<T_Base_Color> colorList = (List<T_Base_Color>)result.get("colorList");//导入成功数据
			param.put("colorList", colorList);
			
			T_Import_Info t_Import_Info = new T_Import_Info();
			t_Import_Info.setIi_success(success);
			t_Import_Info.setIi_fail(fail);
			t_Import_Info.setIi_total(success+fail);
			t_Import_Info.setIi_filename(excel.getOriginalFilename());
			t_Import_Info.setIi_error_filename(errFileName);
			t_Import_Info.setIi_us_id(user.getUs_id());
			t_Import_Info.setIi_sysdate(DateUtil.getCurrentTime());
			t_Import_Info.setIi_type(CommonUtil.IMPROT_COLORTYPE);
			t_Import_Info.setCompanyid(user.getCompanyid());
			param.put("t_Import_Info", t_Import_Info);
			param.put("ii_type", CommonUtil.IMPROT_COLORTYPE);
			
			colorService.save(param);
		}  catch (Exception e){
			e.printStackTrace();
			return ajaxFail("导入失败，请联系管理员！");
		} finally {
			if (sourceWorkBook != null)
				sourceWorkBook.close();
			if (wb_error != null)
				wb_error.close();
			try {
				if (wb != null)
					wb.close();
			} catch (WriteException e) {
				e.printStackTrace();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
		
		return ajaxSuccess();
	}
	
	@RequestMapping(value = "update", method = { RequestMethod.GET, RequestMethod.POST })
	@ResponseBody
	public Object update(T_Base_Color color,HttpServletRequest request,HttpSession session) {
		T_Sys_User user = getUser(session);
		 color.setCompanyid(user.getCompanyid());
		 color.setCr_spell(StringUtil.getSpell(color.getCr_name()));
		 Integer id = colorService.queryByName(color);
		 if(null != id && id > 0){
			return result(EXISTED);
		 }else{
			 colorService.update(color);
			 return ajaxSuccess(color);
		 }
	}
	
	@RequestMapping(value = "del", method = { RequestMethod.GET, RequestMethod.POST })
	@ResponseBody
	public Object del(@RequestParam Integer cr_id,HttpServletRequest request,HttpSession session) {
		 colorService.del(cr_id);
		 return ajaxSuccess();
	}
	
	/**
	 * 商品资料新增、修改查询颜色信息
	 */
	@RequestMapping(value = "colorListByProduct", method = { RequestMethod.GET, RequestMethod.POST })
	@ResponseBody
	public void colorListByProduct(HttpServletRequest request,HttpSession session,HttpServletResponse response) {
		JSONObject jsonObject = new JSONObject();
		PrintWriter out=null;
		try {
	        T_Sys_User user = getUser(session);
	        String name = request.getParameter("colorSearch");
	        String colorCodes= request.getParameter("colorCodes");
	        Map<String,Object> param = new HashMap<String, Object>();
	        param.put(CommonUtil.COMPANYID, user.getCompanyid());
	        param.put("name", StringUtil.decodeString(name));
	        param.put("colorCodes", colorCodes);
	        List<T_Base_Color> list = colorService.colorList(param);
	        out = response.getWriter();
	        if(list != null&&list.size()>0){
				jsonObject.put("color_html",ColorVO.toColorHtmlByList(list));
			}else{
				jsonObject.put("color_html","");
			}
			out.print(jsonObject);
			out.flush();
		} catch (Exception e) {
			e.printStackTrace();
		} finally{
			if(out != null)out.close();
		}
	}
	
	@RequestMapping("to_add_buyProduct")
	public String to_add_buyProduct() {
		return "base/color/add_by_product";
	}
}
